//
//  OMPhotoViewController.m
//  Weibbo
//
//  Created by 李 林刚 on 13-7-21.
//  Copyright (c) 2013年 Omnivores. All rights reserved.
//

#import "OMPhotoViewController.h"

@interface OMPhotoViewController ()
@property (nonatomic, retain)PrePhotoView   *prePhotoView;
@property (nonatomic, retain)EditPhotoView  *editPhotoView;
@property (nonatomic, retain)IFVideoCamera  *filterImageView;

@property (nonatomic, retain)UIImageView    *upAnimationView;
@property (nonatomic, retain)UIImageView    *downAnimationView;

@property (nonatomic, assign)NSInteger       curSelctCellIndex;

@end

@implementation OMPhotoViewController

@synthesize delegate;

@synthesize prePhotoView;
@synthesize editPhotoView;
@synthesize filterImageView;

@synthesize upAnimationView;
@synthesize downAnimationView;
@synthesize curSelctCellIndex;

-(void)dealloc
{
    UIRelease(prePhotoView);
    UIRelease(editPhotoView);
    UIRelease(filterImageView);
    
    UIRelease(upAnimationView);
    UIRelease(downAnimationView);
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(id)initWithCurselectCell:(NSInteger)index
{
    self = [super init];
    if (self) {
        curSelctCellIndex = index;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = UIDarkGrayColor;
    prePhotoView = [[PrePhotoView alloc]initWithFrame:self.view.bounds];
    prePhotoView.delegate = self;
    [self.view addSubview:prePhotoView];
    
    CGRect boundFrame = self.view.bounds;
    boundFrame.origin.x = 320;
    editPhotoView = [[EditPhotoView alloc]initWithFrame:boundFrame];
    editPhotoView.delegate = self;
    [self.view addSubview:editPhotoView];
    
    filterImageView = [[IFVideoCamera alloc]initWithSessionPreset:AVCaptureSessionPresetPhoto cameraPosition:AVCaptureDevicePositionBack highVideoQuality:NO];
    filterImageView.delegate = self;
    filterImageView.gpuImageView.frame = CGRectMake(0, 44, 320, 320);
    [self.view addSubview:filterImageView.gpuImageView];
    
    upAnimationView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 44, 320, 0)];
    upAnimationView.backgroundColor = UIRedColor;
    [self.view addSubview:upAnimationView];
    
    downAnimationView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 364, 320, 0)];
    downAnimationView.backgroundColor = UIBlueColor;
    [self.view addSubview:downAnimationView];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [filterImageView startCameraCapture];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [filterImageView stopCameraCapture];
}

-(void)viewDidUnload
{
    UIRelease(prePhotoView);
    UIRelease(editPhotoView);
    UIRelease(filterImageView);
    UIRelease(upAnimationView);
    UIRelease(downAnimationView);
    [super viewDidUnload];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)ShowEditPhotoViewAnimation
{
    CGRect __block frame;
    [UIView animateWithDuration:0.3 animations:^{
        //cameraView往左侧移出
        frame =  prePhotoView.frame;
        frame.origin.x = -320;
        prePhotoView.frame = frame;
        
        //editPhotoView从右侧移入
        frame = editPhotoView.frame;
        frame.origin.x = 0;
        editPhotoView.frame = frame;
    }
                     completion:^(BOOL finished) {
                     }];
}

-(void)ShowCameraViewShowAnimation
{
    CGRect __block frame;
    [UIView animateWithDuration:0.3 animations:^{
        //editPhotoView往右侧移出
        frame =  editPhotoView.frame;
        frame.origin.x = 320;
        editPhotoView.frame = frame;
        
        //editPhotoView从左侧移入
        frame = prePhotoView.frame;
        frame.origin.x = 0;
        prePhotoView.frame = frame;
    }
                     completion:^(BOOL finished) {
                         [filterImageView cancelAlbumPhotoAndGoBackToNormal];
                     }];
}

#pragma mark - IFVideoCameraDelegate
- (void)IFVideoCameraWillStartCaptureStillImage:(IFVideoCamera *)Camera
{
    CGRect __block frame;
    [UIView animateWithDuration:0.25 animations:^{
        //upImageView往下移ru
        frame =  upAnimationView.frame;
        frame.size.height = 160;
        upAnimationView.frame = frame;
        
        //downImageView往上移入
        frame = downAnimationView.frame;
        frame.origin.y = 204;
        frame.size.height = 160;
        downAnimationView.frame = frame;
    }
                     completion:^(BOOL finished) {
                     }];
}

- (void)IFVideoCameraDidFinishCaptureStillImage:(IFVideoCamera *)Camera
{
    CGRect __block frame;
    [UIView animateWithDuration:0.25 animations:^{
        //upImageView往下移ru
        frame =  upAnimationView.frame;
        frame.size.height = 0;
        upAnimationView.frame = frame;
        
        //downImageView往上移入
        frame = downAnimationView.frame;
        frame.origin.y = 364;
        frame.size.height = 0;
        downAnimationView.frame = frame;
    }
                     completion:^(BOOL finished) {
                         [self ShowEditPhotoViewAnimation];
                     }];
    
}

- (void)IFVideoCameraDidSaveStillImage:(UIImage *)image
{
    [delegate PhotoViewDelegateDidFinishedPhoto:image index:curSelctCellIndex];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Process Album Photo from Image Pick
- (UIImage *)processAlbumPhoto:(NSDictionary *)info {
    UIImage *originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    float original_width = originalImage.size.width;
    float original_height = originalImage.size.height;
    
    if ([info objectForKey:UIImagePickerControllerCropRect] == nil) {
        if (original_width < original_height) {
            /*
             UIGraphicsBeginImageContext(mask.size);
             [ori drawAtPoint:CGPointMake(0,0)];
             [mask drawAtPoint:CGPointMake(0,0)];
             
             UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
             UIGraphicsEndImageContext();
             return newImage;
             */
            return nil;
        } else {
            return nil;
        }
    } else {
        CGRect crop_rect = [[info objectForKey:UIImagePickerControllerCropRect] CGRectValue];
        float crop_width = crop_rect.size.width;
        float crop_height = crop_rect.size.height;
        float crop_x = crop_rect.origin.x;
        float crop_y = crop_rect.origin.y;
        float remaining_width = original_width - crop_x;
        float remaining_height = original_height - crop_y;
        
        // due to a bug in iOS
        if ( (crop_x + crop_width) > original_width) {
            NSLog(@" - a bug in x direction occurred! now we fix it!");
            crop_width = original_width - crop_x;
        }
        if ( (crop_y + crop_height) > original_height) {
            NSLog(@" - a bug in y direction occurred! now we fix it!");
            
            crop_height = original_height - crop_y;
        }
        
        float crop_longer_side = 0.0f;
        
        if (crop_width > crop_height) {
            crop_longer_side = crop_width;
        } else {
            crop_longer_side = crop_height;
        }
        //NSLog(@" - ow = %g, oh = %g", original_width, original_height);
        //NSLog(@" - cx = %g, cy = %g, cw = %g, ch = %g", crop_x, crop_y, crop_width, crop_height);
        //NSLog(@" - cls=%g, rw = %g, rh = %g", crop_longer_side, remaining_width, remaining_height);
        if ( (crop_longer_side <= remaining_width) && (crop_longer_side <= remaining_height) ) {
            UIImage *tmpImage = [originalImage cropImageWithBounds:CGRectMake(crop_x, crop_y, crop_longer_side, crop_longer_side)];
            
            return tmpImage;
        } else if ( (crop_longer_side <= remaining_width) && (crop_longer_side > remaining_height) ) {
            UIImage *tmpImage = [originalImage cropImageWithBounds:CGRectMake(crop_x, crop_y, crop_longer_side, remaining_height)];
            
            float new_y = (crop_longer_side - remaining_height) / 2.0f;
            //UIGraphicsBeginImageContext(CGSizeMake(crop_longer_side, crop_longer_side));
            UIGraphicsBeginImageContextWithOptions(CGSizeMake(crop_longer_side, crop_longer_side), YES, 1.0f);
            [tmpImage drawAtPoint:CGPointMake(0.0f,new_y)];
            
            UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            return newImage;
        } else if ( (crop_longer_side > remaining_width) && (crop_longer_side <= remaining_height) ) {
            UIImage *tmpImage = [originalImage cropImageWithBounds:CGRectMake(crop_x, crop_y, remaining_width, crop_longer_side)];
            
            float new_x = (crop_longer_side - remaining_width) / 2.0f;
            //UIGraphicsBeginImageContext(CGSizeMake(crop_longer_side, crop_longer_side));
            UIGraphicsBeginImageContextWithOptions(CGSizeMake(crop_longer_side, crop_longer_side), YES, 1.0f);
            [tmpImage drawAtPoint:CGPointMake(new_x,0.0f)];
            
            UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            return newImage;
        } else {
            return nil;
        }
    }
}


#pragma mark - UIImagePicker Delegate methods
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    filterImageView.rawImage = [self processAlbumPhoto:info];
    [self.filterImageView switchFilter:IF_NORMAL_FILTER];
    [self ShowEditPhotoViewAnimation];
    [self dismissViewControllerAnimated:YES completion:^(){
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:^(){
        [self.filterImageView cancelAlbumPhotoAndGoBackToNormal];
    }];
}


#pragma mark - CameraDelegate

-(void)PrePhotoViewDelegateEventsTag:(PrePhotoViewEvents)events
{
    switch (events) {
        case PrePhotoViewEventsFlashLight:
        {
            [self.filterImageView SetCameraFlashlight:AVCaptureTorchModeOn];
            break;
        }
        case PrePhotoViewEventsCancel:
        {
            [delegate PhotoViewDelegateCancelPhotoindex:curSelctCellIndex];
            [self.navigationController popViewControllerAnimated:YES];
            break;
        }
        case PrePhotoViewEventsAlbumPhoto:
        {
            UIImagePickerController  *picker = [[UIImagePickerController alloc]init];
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            picker.allowsEditing = YES;
            picker.delegate = self;
            [self presentViewController:picker animated:YES completion:^(){
                [picker release];
            }];
            break;
        }
        case PrePhotoViewEventsShoot:
        {
            [self.filterImageView takePhoto];
            break;
        }
        default:
            break;
    }
}

#pragma mark - EditPhotoView
-(void)EditPhotoViewDelegateButtonClickEvents:(int)tag
{
    switch (tag) {
        case 1:
            [self ShowCameraViewShowAnimation];
            break;
        default:
        {
            [self.filterImageView saveCurrentStillImage];
        }
            break;
    }
}
-(void)EditPhotoViewDelegateChangeFilterType:(int)type
{
    [self.filterImageView switchFilter:type];
}


@end
